import SiderBav from '../sider-nav/index'
import CheckCreative from './check-creative/index'
export default {
  name: 'creativity',
  components: {
    SiderBav,
    CheckCreative
  },
  mounted() {
      this.search();
      this.$store.commit('setHeaderNavActive','创意管理');
  },
  data() {
    return {
      dataList:[],
      total_count:0,
      checkbox:[],
      checkboxAll:'',
      checkboxModal:[],
      currentPage:1,
      planNav: [{
        icon: "",
        text: '选择创意',
        router: '',
        fn:function(){
          // this.$parent.dialogTableVisible=true;
          if(this.$parent.checkbox.length<=0){
              this.$parent.dialogTableVisible=false;
              this.$message.error('请先选择计划信息');
              return;
          }else{
            this.$parent.dialogTableVisible=true;
          }
          // this.$parent.getCreative();
          }
        },
        {
          icon: "",
          text: '移除创意',
          router: '',
          fn:function(){
            this.$parent.deletCreative();
          }
        }
      ],
      payType:'',
      payTypeList: [{
          value: '',
          label: '所有出价方式'
        },
        {
          value: '2',
          label: '按展现付费（CPM）'
        },
        {
          value: '8',
          label: '按点击付费（CPC）'
        }
      ],
      options: [{
          value: '',
          label: '全部状态'
        },
        {
          value: '0',
          label: '暂停'
        },
        {
          value: '1',
          label: '投放中'
        }
      ],
      planStatus:'',
      loading:false,
      dialogTableVisible:false,
      loading:false,
      searchPlanName: "",
      creativeSureLoadding:false,
      sortType:'',
      sort:undefined,
      order:undefined
    }
  },
  filters: {
    planStatus: function (n) {
      return {
        0: "暂停",
        1: '投放中',
        9: '投放结束'
      } [n];
    }
  },
  watch:{
    searchPlanName() {
      this.search();
    },
    planStatus(val) {
      this.search();
    },
    payType(val){
      this.search();
    },
    checkbox(val){
        //this.fileCreativeCheck();
    },
    checkboxAll(val){
        this.checkbox=[];
        if(val){
           for (let index = 0; index < this.dataList.length; index++) {
              const element = this.dataList[index];
              this.checkbox.push(element.id);
           }
        }
    },
    sortType:''
  },
  methods: {
    pagechange(val) {
      this.currentPage=val;
      this.search(val);
    },
    searchOptionsfn() {
      this.searchOptions = {};
      this.searchOptions.url = '/zuanzhan/campaigns';
      this.searchOptions.params = {
        type: this.payType,
        online_status:this.planStatus,
        name:this.searchPlanName
      }
      return this.searchOptions;
    },
    search(page) {
      this.checkbox=[];
      this.checkboxAll=false;
      let _this=this;
      let page_num = page || 1;
      let params = {
        page_num: page_num,
        page_size: 20,
        sort:this.sort,
        order:this.order
      };
      params = Object.assign({}, params, this.searchOptionsfn().params);
      this.dataList = [];
			if(typeof this.source=='function'){
             this.source();//取消请求
      }
      this.loading=true;
      const loading = this.$loading({
        lock: true,
        text: '数据获取中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass:'lodding'
      });
      this.currentPage=page_num;
      this.$http({
          method: 'get',
          url: this.searchOptions.url,
					params: params,
        }).then((data) => {
          this.loading=false;
          loading.close();
          if (!this.$http.interceptors(this, data)) return;

          for (let i = 0, o; o = data.data.data.list[i++];) {
            o['open'] = false;
            o['creativeCheck']=[];
          }
          this.dataList = data.data.data.list;
          this.total_count = data.data.data.total_count;
        })
        .catch(function (error) {
          _this.loading=false;
          loading.close();
          console.log(error);
        });
    },
    creativeSure(){
       if(this.creativeSureLoadding){
            return false;
        };
        let _this=this;
        let data={
          campaign_id:this.checkbox,
          creative_id_list:this.checkboxModal
        };
        if(data.creative_id_list.length<=0){
          this.$message.error('未选择创意');
           return;
        }
        this.creativeSureLoadding=true;
        this.$http({
          method: 'post',
          url: '/zuanzhan/creative/batch-bind',
          data: data,
        }).then((data) => {
          this.creativeSureLoadding=false;
          this.loading=false;
          // if (!this.$http.interceptors(this, data)) return;
          this.dialogTableVisible=false;
          this.search();
          this.$message.success('操作成功');
          this.checkboxModal=[];
          this.checkboxModal=false;
        })
        .catch(function (error) {
          _this.creativeSureLoadding=false;
          console.log(error);
        });
    },
    close(){
      //  this.size='';
      //  this.rank="";
      //  this.status="";
      //  this.name="";
      //  this.size_list=[];
      //  this.gridData=[];
      //  this.total_count_modl=0;
      //  this.checkboxModal=[];
    },
    getCreativeByPlan(element){
        this.$http({
          method: 'get',
          url: '/zuanzhan/creative/lists',
          params:{
            campaign_id:element.id
          },
        }).then((data) => {
            //if (!this.$http.interceptors(this, data)) return;
            element['creativeList']=data.data.data;
            element.open=true;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    closeCreativeTable(element){
       element.open=false;  
    },
    fileCreativeCheckInput(obj){
       const index=this.checkbox.findIndex((value, index, arr)=>{return obj.id==value});
       this.checkbox.splice(index,1);
       this.$nextTick(function () {
          if(obj.creativeCheck.length==obj.creativeList.length){
             this.checkbox.push(obj.id);
          }
        })
    },
    deletCreative(){
        let data=[];
        for (let index = 0; index < this.checkbox.length; index++) {
            const element =  this.checkbox[index];
            data.push({
              campaign_id:element
            });
        }
        for(let index=0;index<this.dataList.length;index++){
          const element =  this.dataList[index];
          if(this.checkbox.findIndex((value,index,arr)=>{return element.id==value})!=-1){
              continue;
          }else{
              if(element.creativeCheck.length>0){
                let obj={
                    campaign_id:element.id,
                    creative_id_list: []
                }
                for (let index = 0; index < element.creativeCheck.length; index++) {
                  const ele = element.creativeCheck[index];
                  obj.creative_id_list.push({
                    adgroup_id:ele.split('/')[1],
                    creative_id:ele.split('/')[0]
                  });
                }
                data.push(obj);
              }
          }
        }
        if(data.length<=0){
          this.$message.error({
            message: '未选择创意'
          });
          return;
        }
        this.$confirm('确定移除选中的创意?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            method: 'post',
            url: '/zuanzhan/creative/batch-unbind',
            data:data,
          }).then((data) => {
              if (!this.$http.interceptors(this, data)) return;
              this.search();
              this.$message({
                type: 'success',
                message: '移除成功!'
              });
          })
          .catch(function (error) {
            console.log(error);
          });
        }).catch(() => {         
        });
    },
    sortfn(key){
      this.sortType=key;
      this.sort=key.split('-')[0];
      this.order=key.split('-')[1];
      this.search();
  }
  }
}